<template>
  <el-dialog title="新建课程" width="800px" :before-close="handleClose">
    <el-form :model="form" label-width="100px">
      <el-form-item label="课程名称">
        <el-input v-model="form.title" placeholder="请输入课程名称"></el-input>
      </el-form-item>
      <el-form-item label="课程分类">
        <el-select v-model="form.categoryName" placeholder="请选择分类">
          <el-option label="基础护理" value="基础护理"></el-option>
          <el-option label="专科护理" value="专科护理"></el-option>
          <el-option label="急救技能" value="急救技能"></el-option>
          <el-option label="护理管理" value="护理管理"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="难度级别">
        <el-select v-model="form.difficulty" placeholder="请选择难度级别">
          <el-option label="入门级" value=0></el-option>
          <el-option label="基础级" value=1></el-option>
          <el-option label="进阶级" value=2></el-option>
          <el-option label="专家级" value=3></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程时长 (小时)">
        <el-input-number v-model="form.lastingTime" :min="0" placeholder="请输入课程时长"></el-input-number>
      </el-form-item>
      <el-form-item label="课程描述">
        <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入课程描述"></el-input>
      </el-form-item>
      <el-form-item label="课程封面">
        <el-upload class="upload-demo" action="#" :auto-upload="false" :show-file-list="false"
          :on-change="handleCoverChange">
          <el-button type="primary">选择文件</el-button>
          <template #tip>
            <div class="el-upload__tip">支持图片文件</div>
          </template>
        </el-upload>
        <div v-if="form.courseCover" class="mt-2">
          <img :src="form.courseCover" alt="课程封面" style="max-width: 150px" />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, toRaw, onMounted } from "vue"; // 引入 toRaw 和 computed
import { useUserStore } from "@/stores/user.js";
import { useCourseStore } from "@/stores/course.js"; // 1. 引入 course store
import { modalControllers } from "@/stores/modalController.js";
import { ElMessage } from "element-plus"; // 2. 引入 ElMessage 用于提示

const modalController = modalControllers();
const userStore = useUserStore();
const courseStore = useCourseStore(); // 3. 实例化 course store

const form = reactive({
  title: "",
  categoryName: "基础护理",
  difficulty: 0,
  lastingTime: 0,
  description: "",
  courseCover: "", // 用于预览的 URL
});
// 4. 新增一个 ref 来存储用户选择的原始 File 对象
const coverFile = ref(null);

const resetForm = () => {
    Object.assign(form, {
        title: "",
        categoryName: "基础护理",
        difficulty: 0,
        lastingTime: 0,
        description: "",
        courseCover: "",
    });
    coverFile.value = null;
    const fileInput = document.querySelector('.upload-demo input[type="file"]');
    if(fileInput) fileInput.value = '';
};

const handleClose = (done) => {
  resetForm(); // 关闭时重置表单
  modalController.closePopup("addCourseModal");
  if (typeof done === 'function') {
    done();
  }
};

// 5. 修改 handleCoverChange 来同时处理预览和文件对象存储
const handleCoverChange = (uploadFile) => {
  // uploadFile 是 Element Plus 的 Upload 组件传递出来的对象
  const rawFile = uploadFile.raw;
  if (rawFile) {
    form.courseCover = URL.createObjectURL(rawFile); // 创建本地预览 URL
    coverFile.value = rawFile; // 存储原始 File 对象用于上传
  }
};

// 6. 新增：处理提交的核心函数
const handleConfirm = () => {
  // 6.1 表单校验
  if (!form.title || !form.title.trim()) {
    ElMessage.warning("请输入课程名称");
    return;
  }
  if (!form.categoryName) {
    ElMessage.warning("请选择课程分类");
    return;
  }
  // 其他字段的校验可以按需添加...

  // 6.2 准备要提交的数据
  // 使用 toRaw() 获取 form ref 的原始对象，避免提交 Vue 的响应式代理
  const courseData = {
    ...toRaw(form),
    createdBy: userStore.user.id,
    status: 0,
  };
  // 删除仅用于前端预览的 courseCover 属性
  delete courseData.courseCover;
  // 2.2 在提交的这一刻，才将当前用户的 ID 赋值给 createdBy
  console.log('提交时 coverFile 的值:', coverFile.value); // 在这里检查，值应该是正确的 File 对象
  // 调用 action
  courseStore.addCourse(courseData, coverFile.value, () => {
    ElMessage.success("课程已成功创建！"); 
    handleClose();
  });
};
</script>
